<?php
/**
 *
 * PHP versions 5
 *
 * Copyright (C)
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software
 * Fundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
 *
 * @author Bastian Schröder <bs@chemanet.de>
 * @version 2007-06-18
 * @package rail
 */
class rail_link extends rail_object {

	/**
	 * Initialization of rail_link.
	 *
	 * @param rail_connector $pAttribute
	 * @param int $pId
	 */
	public function __construct ( $pRailConnector, $pId ) {
		 parent::__construct( $pRailConnector, $pId );
		 
		 // precache link
		 $this->get_link();
	}


	/**
	 * get linked object.
	 *
	 * return rail_object
	 */
	public function get_link () {
		if( !isset( $this->cache[ RAIL_LINK ] ) ){
			$link_relation = $this->get_relations( 'RAIL_LINK' );
			 
			 // throw an exception if more then one target found
			 if( count( $link_relation ) > 1 )
			 	throw new rail_exception( $this, 'found more then one target in RAIL_LINK relation from this object.' );
			 
			 // write rail target to cache
			 if( count( $link_relation ) > 0 )
			 	$this->cache[ RAIL_LINK ] = $link_relation[0];
		}
		
		return $this->cache[ RAIL_LINK ];
	}


	/**
	 * set linked object.
	 *
	 * @exception rail_writepermission_exception
	 * @param rail_object $pRailObject
	 */
	public function set_link ( $pRailObject ) {
		// check write permission
		if( !$this->is_writeable( $this->rail_connector->get_user() ) )
		 	throw new rail_writepermission_exception( $this, $this->rail_connector->get_user() );
		// check wheater new target is a rail_object
		if( !isset($pRailObject) || !$pRailObject instanceof rail_object )
			throw new rail_param_exception( $this, 'link target must be a rail_object.' );

		// remove all existing RAIL_LINK relations
		foreach( $this->get_relations( 'RAIL_LINK' ) as $object )
			$this->remove_relation( $object, 'RAIL_LINK' );
		
		// set new RAIL_LINK relation
		$this->set_relation( $pRailObject, 'RAIL_LINK' );
		$this->cache[ RAIL_LINK ] = $pRailObject;
	}

} // End of rail_link
?>